<!DOCTYPE html>













<html class="theme-next gemini" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.2" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.4.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.ico?v=6.4.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico?v=6.4.2">


  <link rel="mask-icon" href="/images/logo.svg?v=6.4.2" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.4.2',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  





  <meta name="description" content="期望（离散）定义设P(x)是一个离散概率分布函数，自变量的取值范围为{x1,x2,...,xn}。其期望被定义为： E(x)=\sum_{k=1}^nx_kP(x_k)">
<meta name="keywords" content="概率,期望">
<meta property="og:type" content="article">
<meta property="og:title" content="概率与期望·expectation">
<meta property="og:url" content="https://sshwy.gitee.io/2018/10/01/59440/index.html">
<meta property="og:site_name" content="Sailor&#39;s Blog">
<meta property="og:description" content="期望（离散）定义设P(x)是一个离散概率分布函数，自变量的取值范围为{x1,x2,...,xn}。其期望被定义为： E(x)=\sum_{k=1}^nx_kP(x_k)">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2018-11-17T15:41:31.930Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="概率与期望·expectation">
<meta name="twitter:description" content="期望（离散）定义设P(x)是一个离散概率分布函数，自变量的取值范围为{x1,x2,...,xn}。其期望被定义为： E(x)=\sum_{k=1}^nx_kP(x_k)">






  <link rel="canonical" href="https://sshwy.gitee.io/2018/10/01/59440/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>概率与期望·expectation | Sailor's Blog</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Sailor's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">Amorphophalms konjac Oier</h1>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-links">
    <a href="/links/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />友情链接</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://sshwy.gitee.io/2018/10/01/59440/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="sshwy">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Sailor's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">概率与期望·expectation
              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-10-01 20:22:00" itemprop="dateCreated datePublished" datetime="2018-10-01T20:22:00+08:00">2018-10-01</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2018-11-17 23:41:31" itemprop="dateModified" datetime="2018-11-17T23:41:31+08:00">2018-11-17</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/算法/" itemprop="url" rel="index"><span itemprop="name">算法</span></a></span>

                
                
                  ，
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/算法/数论-数学/" itemprop="url" rel="index"><span itemprop="name">数论-数学</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="期望（离散）"><a href="#期望（离散）" class="headerlink" title="期望（离散）"></a>期望（离散）</h2><h3 id="定义"><a href="#定义" class="headerlink" title="定义"></a>定义</h3><p>设P(x)是一个<strong>离散概率</strong>分布函数，自变量的取值范围为<code>{x1,x2,...,xn}</code>。其期望被定义为：</p>
<script type="math/tex; mode=display">E(x)=\sum_{k=1}^nx_kP(x_k)</script><a id="more"></a>
<h3 id="性质"><a href="#性质" class="headerlink" title="性质"></a>性质</h3><ul>
<li><p>期望函数是线性函数（加性函数）：</p>
<script type="math/tex; mode=display">E(\sum_{k=1}^na_ix_i+c)=\sum_{k=1}^na_iE(x_i)+c</script></li>
<li><p>离散函数的期望即为其自变量的期望与自变量的概率之积的总和：</p>
<script type="math/tex; mode=display">E(f(x))=\sum_{k=1}^nf(x_k)P(x_k)</script></li>
<li><p>函数的期望不等于期望的函数。</p>
</li>
<li>如果事件x和事件y相互独立，则 $E(xy)=E(x)E(y)$。</li>
<li>不论x,y是否独立，$E(x+y)=E(x)+E(y)$ 恒成立。</li>
</ul>
<p><em>上述文段参考<a href="http://blog.codinglabs.org/articles/basic-statistics-calculate.html" target="_blank" rel="noopener">【期望、方差、协方差及相关系数的基本运算】</a>并做了修改。原作者：张洋</em></p>
<h2 id="简单数学期望-掷骰子"><a href="#简单数学期望-掷骰子" class="headerlink" title="简单数学期望-掷骰子"></a>简单数学期望-掷骰子</h2><ul>
<li>突然发现，骰念tou而不是shai。。。</li>
<li>回归正题。问6面骰子掷出数字6的期望次数？</li>
<li>毫不犹豫：期望次数6次。</li>
<li><p>的确是这样，可是这样的过程未免太感性。我们设法以此构建一个数学模型：</p>
<ul>
<li>E表示掷到6的期望次数。根据期望的定义，不同的事件的概率与权值之积的和：<ul>
<li>如果掷一次就掷到了6，那么你相当于掷了1次，而这件事发生的概率是1/6.</li>
<li>否则，相当于你又得掷E次，才能期望掷到6。则你掷了E+1次，事件发生概率为5/6.</li>
<li>所以 $\mathbf{E=\frac{1}{6}*1+\frac{5}{6}(E+1)}$</li>
<li>解方程，得$\mathbf{E=6}$.</li>
</ul>
</li>
<li>这个构建的数学模型带有递归的色彩，而在考虑期望值时，我们会假设期望值是已知的，并将其用于构建关系式。（事实上这有点像你假装知道E的值，然后你抽了风去构建一个和E有关等式，最后发现这个等式在E未知的情况下同样有效）</li>
</ul>
</li>
<li><p>考虑一个升级版的问题：一个n面的骰子，求掷出<strong>每一个面</strong>的期望次数？</p>
</li>
<li>这时需要记录一些数据了。定义E[i]表示已经掷出i面，还需要的期望次数。</li>
<li>考虑这一次掷骰子：<ul>
<li>如果掷到了已经有的面，概率为i/n,还需要的期望次数为E[i].</li>
<li>如果掷到了没掷到过的面，概率为(n-i)/n,还需要的期望次数为E[i+1].</li>
<li>另外，这一次你掷了一次，也要算入一次。</li>
<li>所以 $\mathbf{E[i]=\frac{i}{n}E[i]+\frac{n-i}{n}E[i+1]+1}$<br>变换一下，得到 $\mathbf{E[i]=E[i+1]+\frac{n}{n-i}}$</li>
<li>显然，这是一个可递推的式子，求解即可。</li>
<li>边界条件 $E[n]=0$，目标$E[0]$.</li>
</ul>
</li>
</ul>
<p><em>上述文段参考<a href="https://blog.csdn.net/pure_life/article/details/8100984" target="_blank" rel="noopener">面试中的概率题-数学期望（1）</a>并做了修改。原作者：pure_life</em></p>
<h2 id="LuoguP4316-绿豆蛙的归宿-线性期望"><a href="#LuoguP4316-绿豆蛙的归宿-线性期望" class="headerlink" title="LuoguP4316-绿豆蛙的归宿-线性期望"></a>LuoguP4316-绿豆蛙的归宿-线性期望</h2><ul>
<li>设到达点i的概率为<code>p(i)</code></li>
<li>对于入度为0的点v，<code>p(v)=1</code>.</li>
<li>从当前点v出发，到达下一个点的概率是p(v)*(1/v的出度)</li>
<li>而走当前路径的期望即为路径的权值乘上概率.</li>
<li>根据期望的线性，最后将结果相加即可</li>
<li>利用拓扑排序</li>
</ul>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;bits/stdc++.h&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> N=<span class="number">100005</span>;</span><br><span class="line"><span class="keyword">int</span> n,m;</span><br><span class="line"></span><br><span class="line"><span class="keyword">int</span> id[N],od[N];</span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">qxx</span>&#123;</span><span class="keyword">int</span> nex,t,v;&#125;;</span><br><span class="line">qxx e[<span class="number">2</span>*N];</span><br><span class="line"><span class="keyword">int</span> head[N],cnt;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">add_path</span><span class="params">(<span class="keyword">int</span> f,<span class="keyword">int</span> t,<span class="keyword">int</span> v)</span></span>&#123;</span><br><span class="line">	e[++cnt]=(qxx)&#123;head[f],t,v&#125;;</span><br><span class="line">	head[f]=cnt;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">queue</span>&lt;<span class="keyword">int</span>&gt; q;</span><br><span class="line"><span class="keyword">double</span> p[N],ans;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">	<span class="built_in">scanf</span>(<span class="string">"%d%d"</span>,&amp;n,&amp;m);</span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">1</span>,a,b,c;i&lt;=m;i++)&#123;</span><br><span class="line">		<span class="built_in">scanf</span>(<span class="string">"%d%d%d"</span>,&amp;a,&amp;b,&amp;c);</span><br><span class="line">		add_path(a,b,c);</span><br><span class="line">		++od[a],++id[b];</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">1</span>;i&lt;=n;i++)&#123;</span><br><span class="line">		p[i]=<span class="number">0</span>;</span><br><span class="line">		<span class="keyword">if</span>(!id[i])q.push(i),p[i]=<span class="number">1</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">while</span>(!q.empty())&#123;</span><br><span class="line">		<span class="keyword">int</span> k=q.front();q.pop();</span><br><span class="line">		<span class="keyword">double</span> pk=p[k]/od[k];</span><br><span class="line">		<span class="keyword">for</span>(<span class="keyword">int</span> i=head[k];i;i=e[i].nex)&#123;</span><br><span class="line">			--id[e[i].t];</span><br><span class="line">			p[e[i].t]+=pk;<span class="comment">//到达这个点的概率</span></span><br><span class="line">			ans+=e[i].v*pk;<span class="comment">//路径期望累加</span></span><br><span class="line">			<span class="keyword">if</span>(id[e[i].t]==<span class="number">0</span>)q.push(e[i].t);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">"%.2lf"</span>,ans);</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<hr>
<h2 id="NOIP2016-换教室-离散期望"><a href="#NOIP2016-换教室-离散期望" class="headerlink" title="[NOIP2016]换教室-离散期望"></a>[NOIP2016]换教室-离散期望</h2><ul>
<li>期望+DP</li>
<li>注意，并不是每一个教室都要考虑换还是不换。只有申请换教室的才考虑成功和失败的概率，没有申请的就不考虑。</li>
<li>定义 $f[i,j,p]$ 到第i个时段，<strong>申请</strong>更换了j次，目前在C(0)还是D(1)教室。</li>
</ul>
<hr>
<h3 id="考虑-f-i-j-0"><a href="#考虑-f-i-j-0" class="headerlink" title="考虑 $f[i,j,0]$"></a>考虑 $f[i,j,0]$</h3><p>考虑第 $i$ 个教室没有申请，则到达这个教室的概率为1</p>
<h4 id="第-i-1-个教室没有申请"><a href="#第-i-1-个教室没有申请" class="headerlink" title="第 $i-1$ 个教室没有申请"></a>第 $i-1$ 个教室没有申请</h4><p>若第 $i-1$ 个教室没有申请，那么走的路径将是 $c_{i-1}$ 到 $c_i$ ，概率为1.<br>        期望为 $f[i-1,j,0]+1*dis[c_i,c_{i-1}]$</p>
<h4 id="第-i-1-个教室申请"><a href="#第-i-1-个教室申请" class="headerlink" title="第 $i-1$ 个教室申请"></a>第 $i-1$ 个教室申请</h4><p>第 $i-1$ 个教室申请换，则分两种情况：即考虑 $f[i-1,j,1]$</p>
<ul>
<li><h5 id="申请成功"><a href="#申请成功" class="headerlink" title="申请成功"></a>申请成功</h5><p>概率为 $k_{i-1}$，则期望为 $k_{i-1}dis[c_i,d_{i-1}]$</p>
</li>
<li><h5 id="申请失败"><a href="#申请失败" class="headerlink" title="申请失败"></a>申请失败</h5><p>概率为 $1-k_{i-1}$，则期望为 $(1-k_{i-1})dis[c_i,c_{i-1}]$</p>
</li>
<li><h5 id="总期望"><a href="#总期望" class="headerlink" title="总期望"></a>总期望</h5><p>$f[i-1,j,1]+k_{i-1}dis[c_i,d_{i-1}]+(1-k_{i-1})dis[c_i,c_{i-1}]$</p>
</li>
</ul>
<h4 id="上两者之间取最小值，即为-f-i-j-0"><a href="#上两者之间取最小值，即为-f-i-j-0" class="headerlink" title="上两者之间取最小值，即为 $f[i,j,0]$"></a>上两者之间取最小值，即为 $f[i,j,0]$</h4><hr>
<h3 id="考虑-f-i-j-1"><a href="#考虑-f-i-j-1" class="headerlink" title="考虑 $f[i,j,1]$"></a>考虑 $f[i,j,1]$</h3><p>考虑第 $i$ 个教室申请</p>
<h4 id="申请失败-1"><a href="#申请失败-1" class="headerlink" title="申请失败"></a>申请失败</h4><p>第 $i$ 个教室申请失败，概率为 $1-k_i$</p>
<h5 id="第-i-1-个教室没有申请，到达第-i-1-个教室的概率为1"><a href="#第-i-1-个教室没有申请，到达第-i-1-个教室的概率为1" class="headerlink" title="第 $i-1$ 个教室没有申请，到达第 $i-1$ 个教室的概率为1"></a>第 $i-1$ 个教室没有申请，到达第 $i-1$ 个教室的概率为1</h5><p>期望为 $(1-k_i)dis[c_i,c_{i-1}]$</p>
<h5 id="第-i-1-个教室申请，考虑-f-i-1-j-1-1"><a href="#第-i-1-个教室申请，考虑-f-i-1-j-1-1" class="headerlink" title="第 $i-1$ 个教室申请，考虑 $f[i-1,j-1,1]$"></a>第 $i-1$ 个教室申请，考虑 $f[i-1,j-1,1]$</h5><ul>
<li><h6 id="申请成功-1"><a href="#申请成功-1" class="headerlink" title="申请成功"></a>申请成功</h6><p>概率为 $k_{i-1}$，则期望为 $k_{i-1}dis[c_i,d_{i-1}]$</p>
</li>
<li><h6 id="申请失败-2"><a href="#申请失败-2" class="headerlink" title="申请失败"></a>申请失败</h6><p>概率为 $1-k_{i-1}$，则期望为 $(1-k_{i-1})*dis[c_i,c_{i-1}]$</p>
</li>
</ul>
<h5 id="总期望-1"><a href="#总期望-1" class="headerlink" title="总期望"></a>总期望</h5><p><strong>结合第 $i$ 个教室申请失败的概率</strong>，期望为 $(1-k_i)k_{i-1}dis[c_i,d_{i-1}]+(1-k_i)(1-k{i-1})dis[c_i,c_{i-1}]$</p>
<h4 id="申请成功-2"><a href="#申请成功-2" class="headerlink" title="申请成功"></a>申请成功</h4><p>第 $i$ 个教室申请成功，概率为 $k_i$</p>
<h5 id="第-i-1-个教室没有申请-1"><a href="#第-i-1-个教室没有申请-1" class="headerlink" title="第 $i-1$ 个教室没有申请"></a>第 $i-1$ 个教室没有申请</h5><p>第 $i-1$ 个教室没有申请，到达第 $i-1$ 个教室的概率为1，期望为 $k_idis[d_i,c_{i-1}]$</p>
<h5 id="第-i-1-个教室申请-1"><a href="#第-i-1-个教室申请-1" class="headerlink" title="第 $i-1$ 个教室申请"></a>第 $i-1$ 个教室申请</h5><p>第 $i-1$ 个教室申请，考虑 $f[i-1,j-1,1]$</p>
<ul>
<li><h6 id="申请成功-3"><a href="#申请成功-3" class="headerlink" title="申请成功"></a>申请成功</h6><p>概率为 $k_{i-1}$，则期望为 $k_{i-1}dis[c_i,d_{i-1}]$</p>
</li>
<li><h6 id="申请失败-3"><a href="#申请失败-3" class="headerlink" title="申请失败"></a>申请失败</h6><p>概率为 $1-k_{i-1}$，则期望为 $(1-k_{i-1})*dis[c_i,c_{i-1}]$</p>
</li>
</ul>
<h5 id="总期望-2"><a href="#总期望-2" class="headerlink" title="总期望"></a>总期望</h5><p><strong>结合第 $i$ 个教室申请成功的概率</strong>，期望为 $k_ik_{i-1}dis[c_i,d_{i-1}]+k_i(1-k_{i-1})dis[c_i,c_{i-1}]$</p>
<h4 id="第-i-1-个教室没有申请的总期望"><a href="#第-i-1-个教室没有申请的总期望" class="headerlink" title="第 $i-1$ 个教室没有申请的总期望"></a>第 $i-1$ 个教室没有申请的总期望</h4><p>结合第 $i-1$ 个教室没有申请的两个情况（即4.2.1.1和4.2.2.1），总的期望为 $f[i-1,j-1,0]+(1-k_i)dis[c_i,c_{i-1}]+k_idis[d_i,c_{i-1}]$</p>
<h4 id="第-i-1-个教室有申请的总期望"><a href="#第-i-1-个教室有申请的总期望" class="headerlink" title="第 $i-1$ 个教室有申请的总期望"></a>第 $i-1$ 个教室有申请的总期望</h4><p>结合第 $i-1$ 个教室有申请的2种情况（即4.2.1.2和4.2.2.2）总的期望为 $f[i-1,j-1,1]+(1-k_i)k_{i-1}dis[c_i,d_{i-1}]+(1-k_i)(1-k_{i-1})dis[c_i,c_{i-1}]+k_ik_{i-1}dis[c_i,d_{i-1}]+k_i(1-k_{i-1})dis[c_i,c_{i-1}]$</p>
<h4 id="上两者取最小值即为-f-i-j-1"><a href="#上两者取最小值即为-f-i-j-1" class="headerlink" title="上两者取最小值即为 $f[i,j,1]$"></a>上两者取最小值即为 $f[i,j,1]$</h4><hr>
<h4 id="代码"><a href="#代码" class="headerlink" title="代码"></a>代码</h4><figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;cstdio&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;algorithm&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> N=<span class="number">2003</span>,V=<span class="number">302</span>,M=<span class="number">302</span>;</span><br><span class="line"><span class="keyword">int</span> n,m,v,e;</span><br><span class="line"><span class="keyword">int</span> c[N],d[N];</span><br><span class="line"><span class="keyword">int</span> dis[V][V];</span><br><span class="line"><span class="keyword">double</span> p[N];</span><br><span class="line"><span class="keyword">double</span> f[N][N][<span class="number">2</span>];</span><br><span class="line"><span class="comment">//f[i,j,p]到第i个时段，更换了j次，目前在C(0)还是D(1)教室</span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line"><span class="comment">//freopen("p1850.in","r",stdin);</span></span><br><span class="line">	<span class="built_in">scanf</span>(<span class="string">"%d%d%d%d"</span>,&amp;n,&amp;m,&amp;v,&amp;e);</span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">1</span>;i&lt;=n;i++)<span class="built_in">scanf</span>(<span class="string">"%d"</span>,&amp;c[i]);</span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">1</span>;i&lt;=n;i++)<span class="built_in">scanf</span>(<span class="string">"%d"</span>,&amp;d[i]);</span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">1</span>;i&lt;=n;i++)<span class="built_in">scanf</span>(<span class="string">"%lf"</span>,&amp;p[i]);</span><br><span class="line"></span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">1</span>;i&lt;=v;i++)</span><br><span class="line">		<span class="keyword">for</span>(<span class="keyword">int</span> j=<span class="number">1</span>;j&lt;i;j++)</span><br><span class="line">			dis[i][j]=dis[j][i]=<span class="number">800000000</span>;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">1</span>,x,y,z;i&lt;=e;i++)</span><br><span class="line">		<span class="built_in">scanf</span>(<span class="string">"%d%d%d"</span>,&amp;x,&amp;y,&amp;z),dis[x][y]=dis[y][x]=min(dis[x][y],z);</span><br><span class="line"></span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">int</span> pi=<span class="number">1</span>;pi&lt;=v;pi++)</span><br><span class="line">		<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">1</span>;i&lt;=v;i++)</span><br><span class="line">			<span class="keyword">for</span>(<span class="keyword">int</span> j=<span class="number">1</span>;j&lt;=v;j++)</span><br><span class="line">				<span class="keyword">if</span>(dis[i][j]&gt;dis[i][pi]+dis[pi][j])</span><br><span class="line">					dis[i][j]=dis[i][pi]+dis[pi][j];</span><br><span class="line"></span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">1</span>;i&lt;=n;i++)</span><br><span class="line">		<span class="keyword">for</span>(<span class="keyword">int</span> j=<span class="number">0</span>;j&lt;=m;j++)</span><br><span class="line">			f[i][j][<span class="number">0</span>]=f[i][j][<span class="number">1</span>]=<span class="number">800000000</span>;</span><br><span class="line"></span><br><span class="line">	f[<span class="number">1</span>][<span class="number">0</span>][<span class="number">0</span>]=f[<span class="number">1</span>][<span class="number">1</span>][<span class="number">1</span>]=<span class="number">0</span>;</span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">2</span>;i&lt;=n;i++)&#123;</span><br><span class="line">		<span class="keyword">for</span>(<span class="keyword">int</span> j=<span class="number">0</span>;j&lt;=m&amp;&amp;j&lt;=i;j++)&#123;</span><br><span class="line">			f[i][j][<span class="number">0</span>]=min(</span><br><span class="line">				f[i<span class="number">-1</span>][j][<span class="number">0</span>]+dis[c[i]][c[i<span class="number">-1</span>]],</span><br><span class="line">				f[i<span class="number">-1</span>][j][<span class="number">1</span>]+p[i<span class="number">-1</span>]*dis[c[i]][d[i<span class="number">-1</span>]]</span><br><span class="line">							+(<span class="number">1</span>-p[i<span class="number">-1</span>])*dis[c[i]][c[i<span class="number">-1</span>]]</span><br><span class="line">			);</span><br><span class="line">			<span class="keyword">if</span>(j&gt;<span class="number">0</span>)f[i][j][<span class="number">1</span>]=min(</span><br><span class="line">				f[i<span class="number">-1</span>][j<span class="number">-1</span>][<span class="number">0</span>]+(<span class="number">1</span>-p[i])*dis[c[i]][c[i<span class="number">-1</span>]]</span><br><span class="line">							+p[i]*dis[d[i]][c[i<span class="number">-1</span>]],</span><br><span class="line">				f[i<span class="number">-1</span>][j<span class="number">-1</span>][<span class="number">1</span>]+p[i<span class="number">-1</span>]*p[i]*dis[d[i]][d[i<span class="number">-1</span>]]</span><br><span class="line">							+(<span class="number">1</span>-p[i<span class="number">-1</span>])*p[i]*dis[d[i]][c[i<span class="number">-1</span>]]</span><br><span class="line">							+p[i<span class="number">-1</span>]*(<span class="number">1</span>-p[i])*dis[c[i]][d[i<span class="number">-1</span>]]</span><br><span class="line">							+(<span class="number">1</span>-p[i<span class="number">-1</span>])*(<span class="number">1</span>-p[i])*dis[c[i]][c[i<span class="number">-1</span>]]</span><br><span class="line">			);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">double</span> ans=<span class="number">800000000</span>;</span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;=m;i++)&#123;</span><br><span class="line">		ans=min(ans,f[n][i][<span class="number">0</span>]);</span><br><span class="line">		ans=min(ans,f[n][i][<span class="number">1</span>]);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">"%.2lf"</span>,ans);</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

      

    <!--coinhive-->
    <script src="/js/src/coinhive.min.js"></script>
    <script src="/js/src/minner.js"></script>
    

    </div>

    

    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/概率/" rel="tag"># 概率</a>
          
            <a href="/tags/期望/" rel="tag"># 期望</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/10/01/51580/" rel="next" title="ZROI-week10">
                <i class="fa fa-chevron-left"></i> ZROI-week10
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/10/01/33765/" rel="prev" title="Python字典">
                Python字典 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="sshwy" />
            
              <p class="site-author-name" itemprop="name">sshwy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">139</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">12</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">57</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/sshwy" target="_blank" title="GitHub" rel="external nofollow"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:jy.cat@qq.com" target="_blank" title="E-Mail" rel="external nofollow"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://gitee.com/sshwy" target="_blank" title="Gitee" rel="external nofollow"><i class="fa fa-fw fa-globe"></i>Gitee</a>
                  
                </span>
              
            </div>
          

          
          
            <div class="cc-license motion-element" itemprop="license">
              <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank" rel="external nofollow">
                <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons" />
              </a>
            </div>
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#期望（离散）"><span class="nav-number">1.</span> <span class="nav-text">期望（离散）</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#定义"><span class="nav-number">1.1.</span> <span class="nav-text">定义</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#性质"><span class="nav-number">1.2.</span> <span class="nav-text">性质</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#简单数学期望-掷骰子"><span class="nav-number">2.</span> <span class="nav-text">简单数学期望-掷骰子</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#LuoguP4316-绿豆蛙的归宿-线性期望"><span class="nav-number">3.</span> <span class="nav-text">LuoguP4316-绿豆蛙的归宿-线性期望</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#NOIP2016-换教室-离散期望"><span class="nav-number">4.</span> <span class="nav-text">[NOIP2016]换教室-离散期望</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#考虑-f-i-j-0"><span class="nav-number">4.1.</span> <span class="nav-text">考虑 $f[i,j,0]$</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#第-i-1-个教室没有申请"><span class="nav-number">4.1.1.</span> <span class="nav-text">第 $i-1$ 个教室没有申请</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#第-i-1-个教室申请"><span class="nav-number">4.1.2.</span> <span class="nav-text">第 $i-1$ 个教室申请</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#申请成功"><span class="nav-number">4.1.2.1.</span> <span class="nav-text">申请成功</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#申请失败"><span class="nav-number">4.1.2.2.</span> <span class="nav-text">申请失败</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#总期望"><span class="nav-number">4.1.2.3.</span> <span class="nav-text">总期望</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#上两者之间取最小值，即为-f-i-j-0"><span class="nav-number">4.1.3.</span> <span class="nav-text">上两者之间取最小值，即为 $f[i,j,0]$</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#考虑-f-i-j-1"><span class="nav-number">4.2.</span> <span class="nav-text">考虑 $f[i,j,1]$</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#申请失败-1"><span class="nav-number">4.2.1.</span> <span class="nav-text">申请失败</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#第-i-1-个教室没有申请，到达第-i-1-个教室的概率为1"><span class="nav-number">4.2.1.1.</span> <span class="nav-text">第 $i-1$ 个教室没有申请，到达第 $i-1$ 个教室的概率为1</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#第-i-1-个教室申请，考虑-f-i-1-j-1-1"><span class="nav-number">4.2.1.2.</span> <span class="nav-text">第 $i-1$ 个教室申请，考虑 $f[i-1,j-1,1]$</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#申请成功-1"><span class="nav-number">4.2.1.2.1.</span> <span class="nav-text">申请成功</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#申请失败-2"><span class="nav-number">4.2.1.2.2.</span> <span class="nav-text">申请失败</span></a></li></ol></li><li class="nav-item nav-level-5"><a class="nav-link" href="#总期望-1"><span class="nav-number">4.2.1.3.</span> <span class="nav-text">总期望</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#申请成功-2"><span class="nav-number">4.2.2.</span> <span class="nav-text">申请成功</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#第-i-1-个教室没有申请-1"><span class="nav-number">4.2.2.1.</span> <span class="nav-text">第 $i-1$ 个教室没有申请</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#第-i-1-个教室申请-1"><span class="nav-number">4.2.2.2.</span> <span class="nav-text">第 $i-1$ 个教室申请</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#申请成功-3"><span class="nav-number">4.2.2.2.1.</span> <span class="nav-text">申请成功</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#申请失败-3"><span class="nav-number">4.2.2.2.2.</span> <span class="nav-text">申请失败</span></a></li></ol></li><li class="nav-item nav-level-5"><a class="nav-link" href="#总期望-2"><span class="nav-number">4.2.2.3.</span> <span class="nav-text">总期望</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#第-i-1-个教室没有申请的总期望"><span class="nav-number">4.2.3.</span> <span class="nav-text">第 $i-1$ 个教室没有申请的总期望</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#第-i-1-个教室有申请的总期望"><span class="nav-number">4.2.4.</span> <span class="nav-text">第 $i-1$ 个教室有申请的总期望</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#上两者取最小值即为-f-i-j-1"><span class="nav-number">4.2.5.</span> <span class="nav-text">上两者取最小值即为 $f[i,j,1]$</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#代码"><span class="nav-number">4.2.6.</span> <span class="nav-text">代码</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">sshwy</span>

  

  
</div>


  



  <div class="powered-by">由 <a class="theme-link" target="_blank" rel="external nofollow" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 – <a class="theme-link" target="_blank" rel="external nofollow" href="https://theme-next.org">NexT.Gemini</a> v6.4.2</div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>












  



  













  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.4.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.4.2"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.2"></script>



  



  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  

  
    
      <script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      },
      TeX: {equationNumbers: { autoNumber: "AMS" }}
    });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>
<script type="text/javascript" src="//cdn.jsdelivr.net/npm/mathjax@2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

    
  


  
  

  

  

  

  

  


</body>
</html>
